//////////////////////////////////////////////////
// EASIM project
// easim.draw.AddNodeControl
// 6/7/2007 3:03 PM
// Cong Liu
// gzcong@gmail.com

// Copyright (C) 2007
// All rights reserved.
// Refer to LICENSE of JIST (Java In Simulation Time) for terms and conditions of use.

package easim.draw;

import java.util.HashSet;
import java.util.Iterator;

public class AddNodeControl implements Control, jist.runtime.JistAPI.DoNotRewrite
{
	public void mousePressed(Frame frame, int x, int y) {
		Node node = frame.field.getNode(x, y);
		if (node == null) {
			this.addNode(frame, x, y);
			frame.panel.repaint();
		}
	}

	public static Node selected;
	public static int rx;
	public static int ry;

	public void mouseMoved(Frame frame, int x, int y) {
		AddNodeControl.mouseMoved2(frame, x, y);
	}

	public static void mouseMoved2(Frame frame, int x, int y) {
		selected = null;
	}

	public void mouseDragged(Frame frame, int x, int y) {
		AddNodeControl.mouseDragged2(frame, x, y);
	}

	public static void mouseDragged2(Frame frame, int x, int y) {
		if (selected == null) {
			selected = frame.field.getNode(x, y);
			if (selected == null) return;
			rx = x - selected.x;
			ry = y - selected.y;
		}
		selected.x = x - rx;
		selected.y = y - ry;
		frame.panel.repaint();
	}

	private void addNode(Frame frame, int x, int y) {
		HashSet nodes = frame.field.getAllNodes();
		HashSet ids = new HashSet();
		HashSet labels = new HashSet();
    Iterator it = nodes.iterator();
    while (it.hasNext()) {
      Node node = (Node)it.next();
			ids.add(node.id);
			labels.add(node.label);
    }
		Node node = new Node();
		node.x = x;
		node.y = y;
		node.size = frame.nodeSize;
		node.lineStyle = frame.lineStyle.toString();
		node.thickness = frame.thickness;
		for (int i = 1; i < Integer.MAX_VALUE; ++ i) {
			if (ids.contains("" + i)) continue;
			node.id = "" + i;
			break;
		}
		if (frame.nodeLabels == Setting.NodeLabels.ALPHABET) {
			for (int i = 0; i < 26; ++ i) {
				if (labels.contains("" + (char)('A' + i))) continue;
				node.label = "" + (char)('A' + i);
				break;
			}
		}
		if (frame.nodeLabels == Setting.NodeLabels.NUMBERS || node.label == null) {
			for (int i = 1; i < Integer.MAX_VALUE; ++ i) {
				if (labels.contains("" + i)) continue;
				node.label = "" + i;
				break;
			}
		}
		frame.field.addNode(node);
	}

}
